<script setup>
import { ref, onMounted, reactive, toRefs } from 'vue'
import {
  getIngredientListAPI,
  addIngredientAPI,
  updateIngredientAPI,
  getIngredientDetailAPI
} from '@/api/ingredient'

// 列表和分页相关
const state = reactive({
  list: [],
  total: 0,
  page: 1,
  pageSize: 12,
  loading: false,
  searchName: ''
})

const { list, total, page, pageSize, loading, searchName } = toRefs(state)

// 弹窗相关
const dialogVisible = ref({
  add: false,
  edit: false,
  detail: false
})

// 加载状态
const detailLoading = ref(false)

// 食材数据
const ingredient = reactive({
  id: '',
  name: ''
})

// 食材详情及关联菜品
const ingredientDetail = reactive({
  id: 0,
  name: '',
  categoryId: 0,
  calories: 0,
  dishBriefs: []
})

// 获取食材列表
const getIngredientList = async () => {
  if (loading.value) return

  try {
    loading.value = true
    const res = await getIngredientListAPI(
      page.value,
      pageSize.value,
      searchName.value || undefined
    )

    if (res.data.code === 1 && res.data.data) {
      list.value = res.data.data.records || []
      total.value = res.data.data.total || 0
    } else {
      ElMessage.warning('获取数据失败')
      list.value = []
      total.value = 0
    }
  } catch (error) {
    ElMessage.error('获取食材列表失败')
    console.error('获取食材列表错误:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  getIngredientList()
}

// 重置搜索
const handleReset = () => {
  searchName.value = ''
  page.value = 1
  getIngredientList()
}

// 分页改变
const handleCurrentChange = (val) => {
  page.value = val
  getIngredientList()
}

// 打开添加弹窗
const openAddDialog = () => {
  ingredient.id = ''
  ingredient.name = ''
  dialogVisible.value.add = true
}

// 打开编辑弹窗
const openEditDialog = (row) => {
  ingredient.id = row.id
  ingredient.name = row.name
  dialogVisible.value.edit = true
}

// 打开详情弹窗 - 加载食材详情及关联菜品
const openDetailDialog = async (id) => {
  try {
    detailLoading.value = true
    const res = await getIngredientDetailAPI(id)

    if (res.data.code === 1 && res.data.data) {
      Object.assign(ingredientDetail, res.data.data)
      dialogVisible.value.detail = true
    } else {
      ElMessage.warning('获取食材详情失败')
    }
  } catch (error) {
    ElMessage.error('获取食材详情失败')
    console.error('获取食材详情错误:', error)
  } finally {
    detailLoading.value = false
  }
}

// 添加食材
const handleAdd = async () => {
  if (!ingredient.name) {
    ElMessage.warning('请输入食材名称')
    return
  }

  try {
    await addIngredientAPI({ name: ingredient.name })
    ElMessage.success('添加成功')
    dialogVisible.value.add = false
    getIngredientList()
  } catch (error) {
    ElMessage.error('添加失败')
    console.error('添加食材错误:', error)
  }
}

// 更新食材
const handleUpdate = async () => {
  if (!ingredient.name) {
    ElMessage.warning('请输入食材名称')
    return
  }

  try {
    await updateIngredientAPI(ingredient.id, ingredient.name)
    ElMessage.success('更新成功')
    dialogVisible.value.edit = false
    getIngredientList()
  } catch (error) {
    ElMessage.error('更新失败')
    console.error('更新食材错误:', error)
  }
}

// 页面挂载时加载数据
onMounted(() => {
  getIngredientList()
})
</script>

<template>
  <div class="ingredient-management">
    <div class="page-header">
      <h1>食材管理</h1>
      <el-button type="primary" @click="openAddDialog">
        <i class="el-icon-plus"></i> 添加食材
      </el-button>
    </div>

    <div class="search-bar">
      <el-form :inline="true">
        <el-form-item label="食材名称">
          <el-input
            v-model="searchName"
            placeholder="请输入食材名称"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      :data="list"
      style="width: 100%"
      v-loading="loading"
      element-loading-text="加载中..."
      empty-text="暂无食材数据"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="食材名称" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" @click="openDetailDialog(row.id)">
            查看
          </el-button>
          <el-button size="small" type="primary" @click="openEditDialog(row)">
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="page"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加食材弹窗 -->
    <el-dialog title="添加食材" v-model="dialogVisible.add" :width="400">
      <el-form label-width="80px">
        <el-form-item label="食材名称" required>
          <el-input v-model="ingredient.name" placeholder="请输入食材名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible.add = false">取消</el-button>
        <el-button type="primary" @click="handleAdd">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑食材弹窗 -->
    <el-dialog title="编辑食材" v-model="dialogVisible.edit" :width="400">
      <el-form label-width="80px">
        <el-form-item label="ID">
          <el-input v-model="ingredient.id" disabled />
        </el-form-item>
        <el-form-item label="食材名称" required>
          <el-input v-model="ingredient.name" placeholder="请输入食材名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible.edit = false">取消</el-button>
        <el-button type="primary" @click="handleUpdate">确定</el-button>
      </template>
    </el-dialog>

    <!-- 食材详情弹窗 - 包含关联菜品展示 -->
    <el-dialog
      title="食材详情及关联菜品"
      v-model="dialogVisible.detail"
      :width="800"
    >
      <div v-loading="detailLoading" element-loading-text="加载中...">
        <!-- 食材基本信息 -->
        <div class="ingredient-basic-info">
          <el-descriptions column="2" border>
            <el-descriptions-item label="ID">{{
              ingredientDetail.id
            }}</el-descriptions-item>
            <el-descriptions-item label="名称">{{
              ingredientDetail.name
            }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 关联菜品列表 -->
        <div class="related-dishes">
          <h3 style="margin: 16px 0">
            关联菜品 ({{ ingredientDetail.dishBriefs.length }})
          </h3>

          <el-table
            :data="ingredientDetail.dishBriefs"
            border
            empty-text="暂无关联菜品"
            style="width: 100%"
          >
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="dishName" label="菜品名称" />
            <el-table-column prop="merchant" label="商家" />
            <el-table-column prop="location" label="地点" />
            <el-table-column prop="price" label="价格" width="80">
              <template #default="scope">¥{{ scope.row.price }}</template>
            </el-table-column>
            <el-table-column prop="calorie" label="热量" width="80" />
            <el-table-column prop="dishRating" label="评分" width="80" />
            <el-table-column prop="ratingCount" label="评价数" width="80" />
          </el-table>
        </div>
      </div>

      <template #footer>
        <el-button @click="dialogVisible.detail = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.ingredient-management {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    h1 {
      font-size: 1.5rem;
      color: #1a202c;
      margin: 0;
    }
  }

  .search-bar {
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }

  .ingredient-basic-info {
    margin-bottom: 20px;
  }

  .related-dishes {
    margin-top: 10px;
  }
}
</style>
